﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using WebSimplicity.Data.Helpers;
using System.Web.Security;
using System.Web.Mvc;
using System.Diagnostics;
using System.Web;
using System.Web.Routing;

namespace WebSimplicity.Data
{
    public interface IPage
    {
        [Display(Name="Content")]
        [AllowHtml]
        string PageContent { get; set; }
    }
   
    [MetadataType(typeof(IPage))]
    partial class ContentPage: IPage
    {
        static Website web = new Website().Current();
        public void Create()
        {
            Entities db = new Entities(Config.GetConnection("Data.Model"));
            this.CreatedBy = (Guid)Membership.GetUser().ProviderUserKey;
            this.CreatedOn = DateTime.Now;
            this.ModifiedOn = DateTime.Now;
            this.ModifiedBy = (Guid)Membership.GetUser().ProviderUserKey;
            this.WebsiteId = web.WebsiteId;
            this.PageGuid = Guid.NewGuid();
            db.ContentPages.AddObject(this);
            db.SaveChanges();
        }

        public void Update(int id)
        {
            Entities db = new Entities(Config.GetConnection("Data.Model"));
            ContentPage page = db.ContentPages.Single(i => i.PageId == id);
            page.ModifiedOn = DateTime.Now;
            page.ModifiedBy = (Guid)Membership.GetUser().ProviderUserKey;
            page.Description = this.Description;
            page.Keywords = this.Keywords;
            page.MenuTitle = this.MenuTitle;
            page.PageContent = this.PageContent;
            page.ParentId = this.ParentId;
            page.PublishDate = this.PublishDate;
            page.Published = this.Published;
            page.SortOrder = this.SortOrder;
            page.Template = this.Template;
            page.Title = this.Title;
            db.SaveChanges();
        }
    }

    public static class Pages
    {
        static Website web = new Website().Current();
        public static ContentPage GetCurrent()
        {
            string slug = string.Empty;
            Entities db = new Entities(Config.GetConnection("Data.Model"));
            var data =  HttpContext.Current.Request.RequestContext.RouteData;
            if (data.Values.ContainsKey("id"))
            {
                slug = data.Values["id"].ToString();
            }
            if(string.IsNullOrEmpty(slug)){
                return db.ContentPages.Single(i => i.WebsiteId == web.WebsiteId && i.PageId == web.FrontPage);
            }
            return db.ContentPages.Single(i => i.WebsiteId == web.WebsiteId && i.Slug == slug);
        }
    }
}
